package com.wjbgn.electronicnian.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjbgn.electronicnian.convert.NianDoConvert;
import com.wjbgn.electronicnian.dto.NianDTO;
import com.wjbgn.electronicnian.dto.Result;
import com.wjbgn.electronicnian.entity.NianDO;
import com.wjbgn.electronicnian.entity.NianDumplingsDO;
import com.wjbgn.electronicnian.enums.CommonReturnEnum;
import com.wjbgn.electronicnian.mapper.NianDumplingsMapper;
import com.wjbgn.electronicnian.service.NianDumplingsService;
import com.wjbgn.electronicnian.service.NianService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Description:
 * Create Date: 2022-01-20T11:06:12.872423800
 *
 * @author weirx
 * @version 1.0
 */
@Service
public class NianDumplingsServiceImpl extends ServiceImpl<NianDumplingsMapper, NianDumplingsDO> implements NianDumplingsService {

    @Autowired
    private NianService nianService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result eatDumplings(NianDumplingsDO dtoToDo) {
        // 修改饺子数量最先获取的饺子
        List<NianDumplingsDO> list = this.lambdaQuery().eq(NianDumplingsDO::getNianId, dtoToDo.getNianId()).orderByDesc(NianDumplingsDO::getCreateTime).last("limit 1").list();
        if (list.size() == 0) {
            return Result.success(CommonReturnEnum.NO_SELF_WORDS.getCode(), CommonReturnEnum.NO_SELF_WORDS.getName(), null);
        } else {
            if (list.get(0).getDumplingsNum() > 1) {
                this.updateById(new NianDumplingsDO(list.get(0).getId(), list.get(0).getDumplingsNum() - 1));
            } else {
                this.removeById(list.get(0).getId());
            }
        }
        NianDO nianDO = nianService.getById(dtoToDo.getNianId());
        // 增加年兽的饥饿值
        nianService.updateById(new NianDO(dtoToDo.getNianId(), nianDO.getHungryNum() + list.get(0).getHungryNum()));
        return Result.success("我吃了一颗【" + list.get(0).getDumplingsName() + "】,获得了" + list.get(0).getHungryNum() + "点饥饿值");
    }
}